package com.zlm.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Author: Harbour
 * Date: 2021-05-16 20:48
 * Desc: 双重校验锁构建Redis工具类
 */
public class MyRedisUtils {

    // 私有化构造器
    private MyRedisUtils() {}

    private volatile static JedisPool jedisPool;

    public static JedisPool getJedisClient() {
        if (jedisPool == null) {
            synchronized (MyRedisUtils.class) {
                if (jedisPool == null) {
                    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

                    jedisPoolConfig.setMaxTotal(100); // 最大连接数
                    jedisPoolConfig.setMinIdle(20); // 最大空闲
                    jedisPoolConfig.setBlockWhenExhausted(true); // 忙碌时是否等待
                    jedisPoolConfig.setMaxWaitMillis(10000); // 等待时长
                    jedisPoolConfig.setTestOnBorrow(true); // 每次获取连接进行测试

                    String host = MyPropertiesUtils.getProperty("redis.host");
                    String port = MyPropertiesUtils.getProperty("redis.port");

                    jedisPool = new JedisPool(jedisPoolConfig, host, Integer.parseInt(port));
                }
            }
        }
        return jedisPool;
    }

    public static void main(String[] args) {
        Jedis jedis = MyRedisUtils.getJedisClient().getResource();
        System.out.println(jedis.ping());
    }
}
